const Axios = require("axios");

const { MP_ID, API_BASE } = process.env;

const axios = Axios.create({
  baseURL: API_BASE,
});

const linkReg = /https?:\/\/?[\w-]+(\.[\w-]+)+\S+/i;

module.exports = {
  linkReg,
  isLink(val, isIn) {
    if (isIn) return linkReg.test(val);
    return new RegExp(`^${linkReg.source}$`, "i").test(val);
  },
  async getUserInfo(access_token, openid) {
    const { data } = await axios.get(
      "https://api.weixin.qq.com/cgi-bin/user/info",
      {
        params: {
          access_token,
          openid,
          lang: "zh_CN",
        },
      }
    );
    return data;
  },
  async onMpFollow(body) {
    try {
      await axios.post(
        "https://ice.shuqianji.com/v1/user/mp-follow-hook",
        body
      );
    } catch (error) {
      console.log("mp-follow", error.message, body);
    }
  },

  getMpLink(label = "小程序", path = "/pages/index/index") {
    let href = "https://shuqianji.com";
    if (path.includes("?")) {
      href += "?" + path.split("?")[1];
    }
    return `<a href="${href}" data-miniprogram-appid="${MP_ID}" data-miniprogram-path="${path}">${label}</a>`;
    // return label;
  },
  async saveMsg(acc, type) {
    let {
      fromUser: openid,
      createTime: postAt,
      content: text,
      title,
      description: desc,
      url,
      lat,
      lon,
      scale,
      label,
      msgId,
      mediaId,
      thumbMediaId: thumbId,
    } = acc;
    if (type == "link" && text) {
      const mat = linkReg.exec(text);
      url = mat[0].replace(/[，、。,].+/, "");
      title = text.replace(url, "").trim();
      text = null;
    }
    if (url && /mp\.weixin/.test(url)) {
      url = url.replace(/&chksm.+$/, "");
    }
    const extra = {
      postAt,
      text,
      title,
      desc,
      url,
      lat,
      lon,
      scale,
      label,
      mediaId,
      thumbId,
    };
    for (const key in extra) {
      if (!extra[key]) delete extra[key];
    }
    return this.postMsg({
      mp_uid: openid,
      type,
      msg_id: msgId,
      extra,
    });
  },
  async postMsg(body) {
    const { data } = await axios.post("/data/upsert/wx-msg", body);
    return data;
  },
};
